package com.utils;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.criterion.Restrictions;

import com.models.Shared;
import com.models.User;

public final class DB {
	
	static private SessionFactory sf;
	
	static{
		System.out.println("Configurando Banco de Dados");
		AnnotationConfiguration config = new AnnotationConfiguration();
		config.addAnnotatedClass(User.class);
		config.addAnnotatedClass(Shared.class);
		sf = config.buildSessionFactory();
	}

	@Override
	protected void finalize() throws Throwable {
		sf.close();
		super.finalize();
	}

	public static Session getSession() {
		return sf.openSession();
	}

	public static boolean save(Object... objs) {
		boolean res = true;
		Session session = getSession();
		try{
			Transaction tx = session.beginTransaction();
			for (Object obj : objs)
				session.persist(obj);
			tx.commit();
		}catch(Exception e){
			res = false;
			System.out.println("Erro: " + e.getMessage());
		}finally{
			session.close();
		}
		return res;
	}

	@SuppressWarnings("unchecked")
	public static User getUserByName(String name) {
		if(name.equals(""))
			return null;
		Session session = DB.getSession();
		Criteria query = session.createCriteria(User.class);
		query.add(Restrictions.ilike(User.cLogin, name));
		List<User> res = (List<User>)query.list();
		session.close();
		if(res.isEmpty())
			return null;
		else
			return res.get(0);
	}

	public static void addSpace(User user, float space) {
		user.setSpace(user.getSpace() + space);
		Session session = getSession();
		Transaction tx = session.beginTransaction();
		session.update(user);
		tx.commit();
		session.close();
	}
	
}
